package cn.huhst.cas.weisiqian.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import cn.huhst.cas.weisiqian.pojo.PostType;
import cn.huhst.cas.weisiqian.service.PostService;
import cn.huhst.cas.weisiqian.service.PostTypeExistException;
import cn.huhst.cas.weisiqian.util.JSON;

@WebServlet("/AddPostType.do")
public class AddPostType extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(AddPostType.class);
	private PostService postservice = null;

	public AddPostType() {
		super();
		postservice = new PostService();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String posttype = request.getParameter("posttype");
		
		JSON json = new JSON();
		if(posttype != null){
			logger.info("请求添加帖子分类：" + posttype);
			json = PostType.checkNameFormat(posttype, json);
			if(json.isEmpty()){
				boolean result;
				try {
					result = postservice.addPostType(posttype);
					if(result){
						json.putOKMSG("添加帖子分类成功");
						logger.info("添加帖子分类成功");
					}else{
						json.putErrorMSG("添加帖子分类失败");
						logger.error("添加帖子分类失败");
					}
				} catch (PostTypeExistException e) {
					json.putErrorMSG(posttype + "帖子分类已存在");
					logger.error(posttype + " 帖子分类已存在");
				}
			}else{
				json.putErrorMSG("帖子分类格式不符合要求");
				logger.error("帖子分类格式不符合要求");
			}
		}else{
			json.putErrorMSG("帖子分类为空");
			logger.error("添加帖子分类失败，帖子分类为空");
		}
		
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(json);
	}

}
